package com.koushikdutta.ion.loader;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.text.TextUtils;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.future.SimpleFuture;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.stream.InputStreamDataEmitter;
import com.koushikdutta.async.util.StreamUtility;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Loader.LoaderEmitter;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import com.koushikdutta.ion.bitmap.IonBitmapCache;
import java.io.InputStream;

public class ResourceLoader extends StreamLoader {

    private static class Resource {
        int id;
        Resources res;

        private Resource() {
        }
    }

    private static Resource lookupResource(Context context, String uri) throws Exception {
        Uri u = Uri.parse(uri);
        if (u.getPathSegments() == null) {
            throw new IllegalArgumentException("uri is not a valid resource uri");
        }
        int id;
        String pkg = u.getAuthority();
        Resources res = context.createPackageContext(pkg, 0).getResources();
        if (u.getPathSegments().size() == 1) {
            id = Integer.valueOf((String) u.getPathSegments().get(0)).intValue();
        } else if (u.getPathSegments().size() == 2) {
            id = res.getIdentifier((String) u.getPathSegments().get(1), (String) u.getPathSegments().get(0), pkg);
            if (id == 0) {
                throw new IllegalArgumentException("resource not found in given package");
            }
        } else {
            throw new IllegalArgumentException("uri is not a valid resource uri");
        }
        Resource ret = new Resource();
        ret.res = res;
        ret.id = id;
        return ret;
    }

    public Future<BitmapInfo> loadBitmap(Context context, Ion ion, String key, String uri, int resizeWidth, int resizeHeight, boolean animateGif) {
        if (uri == null || !uri.startsWith("android.resource:/")) {
            return null;
        }
        final Future<BitmapInfo> ret = new SimpleFuture();
        final Context context2 = context;
        final String str = uri;
        final Ion ion2 = ion;
        final int i = resizeWidth;
        final int i2 = resizeHeight;
        final boolean z = animateGif;
        final String str2 = key;
        Ion.getBitmapLoadExecutorService().execute(new Runnable() {
            public void run() {
                try {
                    Object info;
                    Resource res = ResourceLoader.lookupResource(context2, str);
                    Options options = ion2.getBitmapCache().prepareBitmapOptions(res.res, res.id, i, i2);
                    Point size = new Point(options.outWidth, options.outHeight);
                    if (z && TextUtils.equals("image/gif", options.outMimeType)) {
                        info = ResourceLoader.this.loadGif(str2, size, res.res.openRawResource(res.id), options);
                        StreamUtility.closeQuietly(res.res.openRawResource(res.id));
                    } else {
                        if (IonBitmapCache.loadBitmap(res.res, res.id, options) == null) {
                            throw new Exception("Bitmap failed to load");
                        }
                        info = new BitmapInfo(str2, options.outMimeType, new Bitmap[]{bitmap}, size);
                    }
                    info.loadedFrom = 1;
                    ret.setComplete(info);
                } catch (OutOfMemoryError e) {
                    ret.setComplete(new Exception(e), null);
                } catch (Exception e2) {
                    ret.setComplete(e2);
                } catch (Throwable th) {
                    StreamUtility.closeQuietly(in);
                }
            }
        });
        return ret;
    }

    public Future<DataEmitter> load(Ion ion, AsyncHttpRequest request, FutureCallback<LoaderEmitter> callback) {
        if (!request.getUri().getScheme().startsWith("android.resource:/")) {
            return null;
        }
        final Future<DataEmitter> ret = new InputStreamDataEmitterFuture();
        final Ion ion2 = ion;
        final AsyncHttpRequest asyncHttpRequest = request;
        final FutureCallback<LoaderEmitter> futureCallback = callback;
        ion.getHttpClient().getServer().post(new Runnable() {
            public void run() {
                try {
                    Resource res = ResourceLoader.lookupResource(ion2.getContext(), asyncHttpRequest.getUri().toString());
                    InputStream stream = res.res.openRawResource(res.id);
                    if (stream == null) {
                        throw new Exception("Unable to load content stream");
                    }
                    int available = stream.available();
                    InputStreamDataEmitter emitter = new InputStreamDataEmitter(ion2.getHttpClient().getServer(), stream);
                    ret.setComplete((Object) emitter);
                    futureCallback.onCompleted(null, new LoaderEmitter(emitter, (long) available, 1, null, null));
                } catch (Exception e) {
                    ret.setComplete(e);
                    futureCallback.onCompleted(e, null);
                }
            }
        });
        return ret;
    }
}
